//JavaScript代码区域
layui.use(['laydate','form','table'], function() {
	var laydate = layui.laydate;
	var form = layui.form;
	var table = layui.table;
	
	var dtt = {}; //搜索条件
	
	initTable(dtt);
	queryTypeNameSelect();
	$('#layui-table-filter input[type="text"]').attr('disabled',true);
	$('#layui-table-filter select').attr('disabled',true);
	
	laydate.render({
		elem: '#payTime',
		theme: 'molv',
		showBottom: false,
		calendar: true,
		trigger: 'click',
		value: new Date(),
		change: function(value, date){
			lay('#payTime').html(value);
		}
	});
	 laydate.render({
	    elem: '#payStart',
	    theme: 'molv',
	    showBottom: false,
	    calendar: true,
	    trigger: 'click',
	    change: function(value, date){
	    	lay('#payStart').html(value);
	    }
	  });
	 laydate.render({
	    elem: '#payEnd',
	    theme: 'molv',
	    showBottom: false,
	    calendar: true,
	    trigger: 'click',
	    change: function(value, date){
	    	lay('#payEnd').html(value);
	    }
	  });
	 // 获取快递公司下拉框数据
	 $.ajax({
		url: '/account/query/express/company',
		type: 'post',
		dataType: 'json',
		success: function(data){
			var html = '<option value="">请选择</option>';
			$.each(data, function(i,item){
				html += '<option value="' + item.expressCode + '">' + item.expressName + '</option>';
			});
			
			$('#expressCode').empty();
			$('#expressCode').append(html);
			 // 渲染下拉框
			form.render();
		}
	});
	form.on('submit(accountSubmit)', function(data){
		if(!valiteForm()) return false;
		var params = $('#accountForm').serializeArray();
		$.ajax({
			url : "/account/save",
			type : "post",
			data : params,
			beforeSend : function () {
            	this.layerIndex = layer.load(0, { shade: [0.5, '#393D49'] });
          	},
			success : function(data) {
				layer.close(this.layerIndex);
				if (data.success) {
					layer.msg('数据保存成功!', {icon: 6});
					 window.location.reload();
				}else{
					layer.msg('操作失败!', {icon: 5});
				}
			},
			complete : function () {
				layer.close(this.layerIndex);
			}
		})
		 return false;
	});
	form.on('checkbox(typeCode)',function(obj){
		for (var i = 0; i < $(this).parent().nextAll().children().length; i++) {
			if (obj.elem.checked) {
				$(this).parent().nextAll().children().prop('disabled',false);
				$(this).parent().nextAll().children().children().attr('disabled',false);
				$(this).parent().nextAll().children().children().find('select').attr('disabled',false);
			} else {
				$(this).parent().nextAll().children().prop('disabled',true);
				$(this).parent().nextAll().children().children().attr('disabled',true);
				$(this).parent().nextAll().children().children().find('select').attr('disabled',true);
			}
			form.render('select');
			valiteMoney();
		}
	});
	
	// 流水列表总览查询
	 $("#searchBtn").click(function(){
		var payStart = $('#payStart').val();
		var payEnd = $('#payEnd').val();
		var typeCode = $('#typeCode').val();
		
		dtt = {
			payStart : payStart,
			payEnd : payEnd,
			typeCode : typeCode
		}
		initTable(dtt);
	})
	
	function initTable(dtt){
		table.render({
			elem: '#accountTable',
			height: 480,
			url:'/account/query/account/list',
			title: '流水数据列表总览',
			page: false, //开启分页
	        totalRow: false, //开启合计行
	        limit:10,
			limits: [10,20,50],
	        where: dtt,
	        method:'POST',
			cols: [ [ //表头
				{field:'pkid', title:'pkid', fixed: 'left', unresize: true,hide: true},
				{field:'payCode', title:'支出编号',  unresize: true},
				{field:'payTime', title:'支出日期',  unresize: true, templet: function(e){
					var date = new Date(e.payTime)
					return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
	      		}},
				{field:'realName', title:'支出者姓名',  unresize: true},
				{field:'typeName', title:'支出类型',  unresize: true, templet: function(e){
					if (e.typeName.length <= 10) {
						return '<span>' + e.typeName + '</span>';
					} else
						return '<a title="' + e.typeName + '">' + e.typeName.substring(0,7) + '...</a>'
	      		}},
				{field:'sumPayMoney', title:'支出总额',  unresize: true},
				{fixed: 'right', title:'操作', toolbar: '#accountBar', width: 80,  unresize: true}
			] ],
			page: {
				layout: ['count', 'prev', 'page', 'next', 'skip'], //自定义分页布局
				groups: 5, //只显示 1 个连续页码
				first: '首页', //不显示首页
				last: '尾页', //不显示尾页
				elem:'bottomPage'
			},
			parseData: function(res){
				return {
	                "code": res.code, //解析接口状态
	                "msg": res.message, //解析提示文本
	                "count": res.count, //解析数据长度
	                "data": res.data //解析数据列表
	     	   };
			},
			response: {
  	    	    statusName: 'code' //规定数据状态的字段名称，默认：code
  	    	    ,statusCode: 0 //规定成功的状态码，默认：0
  	    	    ,msgName: 'msg' //规定状态信息的字段名称，默认：msg
  	    	    ,countName: 'count' //规定数据总数的字段名称，默认：count
  	    	    ,dataName: 'data' //规定数据列表的字段名称，默认：data
      	  	}, 
			done: function(res){
				
			}
		});
	}
   //监听行工具事件
  table.on('tool(accountTable)', function(obj){
    var data = obj.data, //获得当前行数据
    layEvent = obj.event; //获得 lay-event 对应的值
    if(layEvent === 'detail'){
		window.open('/account/detail?pkid=' + data.pkid,'_blank');
    } 
  });
});

function queryTypeNameSelect(){
	// 查询流水列表总览支出类型下拉框数据
	 $.ajax({
		url: '/account/query/type/name',
		type: 'post',
		dataType: 'json',
		success: function(data){
			var html = '<option value="">请选择</option>';
			$.each(data, function(i,item){
				html += '<option value="' + item.typeCode + '">' + item.typeName + '</option>';
			});
			
			$('#typeCode').empty();
			$('#typeCode').append(html);
		}
	});
}


function valiteNumber(obj){
	var validAmount = $(obj).val();
    var valiteAmount = /^(([1-9]\d*)|\d)(\.\d{1,2})?$/;
	if(validAmount != null && validAmount != '' && valiteAmount.test(validAmount)==false){
    	layer.alert('金额必须为数字格式!', {icon: 2});
    	return;
   }
	valiteMoney();
}
function valiteMoney() {
	var payMoney = 0;
	for(var i = 0; i < $('.pay-money').length; i++){
		var paymoney = $('#payMoney' + i).val();
		if ($('#typeCode' + i).is(':checked')) {
			if (paymoney != null && paymoney != '') {
				payMoney = payMoney + parseFloat(paymoney);
			} 
		} 
	}
	 $('#sumPayMoney').val(payMoney);
}
function valiteForm(){
	var expressCode = $('#expressCode').val();
	var remake = $('#remake2').val();
	
	for(var i = 0; i < $('.pay-money').length; i++){
		var paymoney = $('#payMoney' + i).val();
		if ($('#typeCode' + i).is(':checked') && (paymoney == null || paymoney == '')) {
			layer.alert('支出类型选择时支出金额必填!', {icon: 2});
			$('#payMoney' + i).css('border-color','red');
        	return false;
		}
	}
	if (expressCode == 'QT' && (remake == '' || remake == null)) {
		layer.alert('快递选择其他时备注必填!', {icon: 2});
		$('#remake2').css('border-color','red');
    	return false;
	}
	return true;
}